# coding:UTF-8

'''
Created on 2015年4月7日

@author: Administrator
'''
from django.http.response import HttpResponse
from youaiwang.settings import BASE_DIR
import re, json, time, os, hashlib


def judgeAction(request):
    if request.method == "GET":
        if request.GET.get('action', '') == 'config':
            configFilePath = BASE_DIR + '/static/index/plug/ueditor/php/config.json'
            configFile = open(configFilePath, 'r')
            try:
                jsonString = configFile.read()
                jsonString = re.sub("\/\*[\s\S]+?\*\/", "", jsonString)
                configFile.close()
                return HttpResponse(jsonString)

            except:
                raise




    else:

        return dealUploadFile(request)


def dealUploadFile(request):
    result = {
        "state": "SUCCESS",
        "url": "",
        "title": "",
        "original": "",
        "type": "image/gif",
        "size": "",
    }

    path = 'static/upload/article/pic/'
    path = path + time.strftime("%Y%m%d") + "/"
    linux_path = BASE_DIR + '/' + path
    if (not os.path.exists(linux_path)):
        os.makedirs(linux_path)

    filename = hashlib.md5(str(time.time())).hexdigest()
    fp = request.FILES['upfile']
    fp_name = fp.name.encode("UTF-8")
    fp_name = fp_name.split(".")
    fp_name = filename + "." + fp_name[len(fp_name) - 1]
    result['size'] = fp.size
    result['original'] = fp_name
    result['url'] = "/" + path + fp_name

    save_fp = open(linux_path + fp_name, 'wb')
    save_fp.write(fp.read())
    save_fp.close()
    return HttpResponse(json.dumps(result))


if __name__ == '__main__':
    pass
